#include "qRegShape.h"
#include "point.h"

#include <QResizeEvent>
#include <QPaintEvent>
#include <QPainter>
#include <QPolygonF>
#include <QStyleOption>
#include <QStylePainter>
#include <QObjectUserData>

QRegShape::QRegShape(QWidget *parent) :
    QWidget(parent), QBody(new RegularShape(0)), shape(static_cast<RegularShape*>(body))
{
    setMinimumSize(50, 50);
    setSizePolicy(QSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding));

}

uchar QRegShape::sides() const
{
    return shape->sides();
}

void QRegShape::sides(int s)
{
    shape->sides(s);
    update();
}

void QRegShape::resizeEvent(QResizeEvent *e)
{
    QWidget::resizeEvent(e);
    const QSizeF s = e->size() / 2;

    shape->size(std::min(s.width(), s.height()));
    position(s.width(), s.height());
}

void QRegShape::paintEvent(QPaintEvent *e)
{
    QWidget::paintEvent(e);

    QStyleOption opts;
    opts.init(this);
    QStylePainter stylePainter(this);
    stylePainter.drawPrimitive(QStyle::PE_Widget, opts);
    QPainter p(this);

    p.setBrush(QBrush(Qt::red));
    QPolygonF poly;
    for(const auto &v : shape->vertices())
        poly.append(QPointF(v[0], v[1]));
    p.drawPolygon(poly);

}

void QRegShape::mouseDoubleClickEvent(QMouseEvent *e)
{
    Point pt(e->x(), e->y());
    vector3 ignoreV;
    scalar ignoreS;
    if (intersect(pt, *shape, ignoreV, ignoreS, pt.position() - shape->position()))
        emit dblClicked(shape);
}
